package com.leetcode.partition6;

import com.leetcode.common.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author `RKC`
 * @date 2021/8/16 10:40
 */
public class LC515在每个树行中找最大值 {

    public static List<Integer> largestValues(TreeNode root) {
        return bfs(root);
    }

    private static List<Integer> bfs(TreeNode root) {
        List<Integer> answer = new ArrayList<>();
        if (root == null) return answer;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.pollFirst();
                max = Math.max(max, cur.val);
                if (cur.left != null) queue.add(cur.left);
                if (cur.right != null) queue.add(cur.right);
            }
            answer.add(max);
        }
        return answer;
    }
}
